package com.colorful.insuranceproject.microDrug;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.colorful.insuranceproject.R;
import com.colorful.insuranceproject.adapter.CityListBean;
import com.colorful.insuranceproject.adapter.DrugAddressAdapter;
import com.colorful.insuranceproject.base.PLEActivity;
import com.colorful.insuranceproject.base.SingleLocationMapActivity;
import com.colorful.insuranceproject.base.CityChooseActivity;
import com.colorful.insuranceproject.bean.DrugAddressBean;
import com.colorful.insuranceproject.consts.CodeTable;
import com.colorful.insuranceproject.request.MicroDrugRequest;
import com.lovely3x.common.activities.refresh.CanLoadMore;
import com.lovely3x.common.activities.refresh.CanRefresh;
import com.lovely3x.common.beans.LocationWrapper;
import com.lovely3x.common.managements.LocationManager;
import com.lovely3x.common.utils.Response;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by handsome-Bob on 2017/8/18.
 * 药店地址
 */
public class DrugAddressActivity extends PLEActivity implements CanRefresh, CanLoadMore, View.OnClickListener, AdapterView.OnItemClickListener {

    private static final int GET_DRUG_ADDRESS_URL = 0X1;

    private static final int REQUEST_CODE = 10000;

    public static final String EXTRA_POSITION = "extra_position";

    private DrugAddressAdapter drugAddressAdapter;

    private MicroDrugRequest microDrugRequest;

    @Bind(R.id.lv_drug_address)
    ListView lvDrugAddress;

    @Bind(R.id.fl_fragment_list_empty_container)
    ViewGroup container;

    TextView city;

    CityListBean cb;

    int isChild;

    @Override
    protected int getContentView() {
        return R.layout.common_list;
    }

    @Override
    protected void initViews() {
        super.initViews();
        ButterKnife.bind(this);
        setTitle(getString(R.string.micro_address));
        addRightBtn(cb.getAreaName(), R.id.city);
        city = (TextView) findViewById(R.id.city);
        Drawable drawable = ContextCompat.getDrawable(mActivity,R.drawable.down_arrow_white);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//这句一定要加
        city.setCompoundDrawablePadding(10);//设置图片和text之间的间距
        city.setCompoundDrawables(drawable, null, null, null);//setCompoundDrawables用来设置图片显示在文本的哪一端
        city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                launchActivityForResult(CityChooseActivity.class, REQUEST_CODE, CityChooseActivity.EXTRA_POSITION, cb);
            }
        });
    }

    @Override
    protected void onInitExtras(@NonNull Bundle bundle) {
        super.onInitExtras(bundle);
        cb = bundle.getParcelable(EXTRA_POSITION);
    }

    @Override
    protected void onViewInitialized() {
        cb.setNowCity(cb.getAreaName());//当前区域城市
        cb.setNowCityId(cb.getAreaId());//当前区域ID


        microDrugRequest = new MicroDrugRequest(getHandler());
        drugAddressAdapter = new DrugAddressAdapter(null, mActivity);
        lvDrugAddress.setAdapter(drugAddressAdapter);
        lvDrugAddress.setOnItemClickListener(this);

        currentIndex = DEFAULT_POST_FIRST_PAGE;
        handleLoadingContent();
        getPageData();
    }

    private void getPageData() {
        LocationManager.getInstance().start();
        LocationWrapper loc = LocationManager.getInstance().getCurrentLocation();
        if (loc == null) loc = new LocationWrapper();
        double latitude = loc.getLatitude();
        double longitude = loc.getLongitude();
        String areaName;
        if (isChild == 0) {
            areaName = cb.getNowCity();
        } else {
            areaName = cb.getAreaName();
        }
        if (microDrugRequest != null) {
            microDrugRequest.getDrugAddressList(latitude, longitude, isChild, areaName, currentIndex, GET_DRUG_ADDRESS_URL);
        }
    }

    @Override
    protected void handleResponseMessage(Message msg, Response response) {
        super.handleResponseMessage(msg, response);
        switch (msg.what) {
            case GET_DRUG_ADDRESS_URL:
                LocationManager.getInstance().stop();
                handleRefreshState(response, drugAddressAdapter);
                if (response.isSuccessful) {
                    onContentStatusChanged(LOADING_SUCCESSFUL);
                    if (currentIndex == 0 && ((List<DrugAddressBean>) response.obj).size() == 0) {
                        onContentStatusChanged(LOADING_FAILURE, getString(R.string.not_find_data), this);
                    } else {
                        setPageData((List<DrugAddressBean>) response.obj, response.addtional);
                    }
                } else {
                    if (response.addtional == DEFAULT_POST_FIRST_PAGE) {
                        onContentStatusChanged(LOADING_FAILURE, CodeTable.getInstance().getCodeDescription(response), this);
                    }
                    break;
                }
        }
    }

    private void setPageData(List<DrugAddressBean> obj, int index) {
        switch (index) {
            case DEFAULT_POST_FIRST_PAGE:
                drugAddressAdapter.setData(obj);
                break;
            default:
                drugAddressAdapter.addDataToLast(obj);
                break;
        }
    }

    @Override
    public void restoreInstanceOnCreateBefore(@NonNull Bundle savedInstance) {

    }

    @Override
    public void restoreInstanceOnCreateAfter(@NonNull Bundle savedInstance) {

    }

    @Override
    public void onBeginRefresh() {
        currentIndex = DEFAULT_POST_FIRST_PAGE;
        getPageData();
    }

    @Override
    public void onBeginLoadMore() {
        currentIndex++;
        getPageData();
    }

    @Override
    protected ViewGroup getEmptyContainerView() {
        return container;
    }

    @Override
    public void onClick(View v) {
        currentIndex = DEFAULT_POST_FIRST_PAGE;
        handleLoadingContent();
        getPageData();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //  跳转到地图页面
        DrugAddressBean bean = drugAddressAdapter.getItem(position);
        launchActivity(SingleLocationMapActivity.class, SingleLocationMapActivity.EXTRA_DEFAULT_LOCATION, bean);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            cb = data.getParcelableExtra("id");
            isChild = cb.getIsChild();
            if (isChild == 0) {
                city.setText(cb.getNowCity());
            } else {
                city.setText(cb.getAreaName());
            }
            currentIndex = DEFAULT_POST_FIRST_PAGE;
            handleLoadingContent();
            getPageData();
        }
    }
}
